package com.xinsoft.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinsoft.common.exception.BDException;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.CusDeviceBreakdownDTO;
import com.xinsoft.entity.dto.CusDeviceBreakdownPageParam;
import com.xinsoft.entity.dto.CusRepairApproveDTO;
import com.xinsoft.entity.dto.CusRepaireDTO;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.CusDeviceBreakdownVo;
import com.xinsoft.entity.vo.CusRepaireVo;
import com.xinsoft.mapper.CusDeviceBreakdownMapper;
import com.xinsoft.service.*;
import com.xinsoft.utils.TokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author hsm
* @description 针对表【cus_device_breakdown(设备故障)】的数据库操作Service实现
* @createDate 2023-06-19 16:05:54
*/
@Service
public class CusDeviceBreakdownServiceImpl extends ServiceImpl<CusDeviceBreakdownMapper, CusDeviceBreakdown>
    implements CusDeviceBreakdownService{

    @Resource
    public CusDocumentService cusDocumentService;

    @Resource
    public CusDeviceService cusDeviceService;

    @Resource
    public SysDictionaryService sysDictionaryService;

    @Resource
    public SysUserService sysUserService;

    @Autowired
    private CusRepaireService cusRepaireService;

    @Autowired
    private CusRepairApproveService cusRepairApproveService;

    @Autowired
    private SysFileHisService sysFileHisService;

    @Override
    public IPage<CusDeviceBreakdownVo> findPageListByParam(CusDeviceBreakdownPageParam param) {
        // 我发起的
        if(Objects.equals(param.getType(),0)){
            param.setUserId(TokenUtil.getUserId());
        }
        // 待处理
        if(Objects.equals(param.getType(),1)){
            List status = new ArrayList<>();
            status.add(1);
            status.add(4);
            // 待处理页签
            param.setStatus(status);
            param.setRepaireUserId(TokenUtil.getUserId());
        }
        if(Objects.equals(param.getType(),2)){
            param.setRepaireStatus(2);
        }
        //分页
        Page<CusDeviceBreakdownVo> page = new Page<>(param.getCurrentPage(), param.getPageSize());
        //查询分页
        IPage<CusDeviceBreakdownVo> pageList = this.baseMapper.findListByParam(page, param);

        return pageList;
    }

    @Override
    public CusDeviceBreakdown addCusDeviceBreakdown(CusDeviceBreakdownDTO cusDeviceBreakdownDTO) {
        if(cusDeviceBreakdownDTO.getRepaireStatus()==null){
            cusDeviceBreakdownDTO.setRepaireStatus(Const.RepairStatus.STAGING);
        }
        CusDeviceBreakdown entity= new CusDeviceBreakdown();
        BeanUtils.copyProperties(cusDeviceBreakdownDTO,entity);
        entity.setSendRepaireTime(new Date());
        save(entity);

        //保存图片
        if(CollectionUtil.isNotEmpty(cusDeviceBreakdownDTO.getCusDocumentListDocument())){
            for (CusDocument cusDocument : cusDeviceBreakdownDTO.getCusDocumentListDocument()) {
                cusDocument.setDeviceRefId(entity.getId());
                cusDocument.setDeviceRefType(Const.DeviceRefType.DEVICE_BREAKDOWN_FILE);
            }
            cusDocumentService.saveBatch(cusDeviceBreakdownDTO.getCusDocumentListDocument());
        }
        cusDeviceBreakdownDTO.setDeviceId(entity.getId());
        return entity;
    }

    @Override
    public CusDeviceBreakdown editCusDeviceBreakdown(CusDeviceBreakdownDTO cusDeviceBreakdownDTO) {
        CusDeviceBreakdown entity= getById(cusDeviceBreakdownDTO.getId());
        if(!Objects.equals(entity.getRepaireStatus(),Const.RepairStatus.STAGING)){
            throw new BDException("操作失败，只能修改暂存的故障报修！");
        }

        BeanUtils.copyProperties(cusDeviceBreakdownDTO,entity);
        entity.setId(cusDeviceBreakdownDTO.getId());
        updateById(entity);

        //删除图片关系
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_ref_id",entity.getId());
        queryWrapper.eq("device_ref_type",Const.DeviceRefType.DEVICE_BREAKDOWN_FILE);
        cusDocumentService.remove(queryWrapper);
        //保存图片
        if(CollectionUtil.isNotEmpty(cusDeviceBreakdownDTO.getCusDocumentListDocument())){
            for (CusDocument cusDocument : cusDeviceBreakdownDTO.getCusDocumentListDocument()) {
                cusDocument.setDeviceRefId(entity.getId());
                cusDocument.setDeviceRefType(Const.DeviceRefType.DEVICE_BREAKDOWN_FILE);
            }
            cusDocumentService.saveBatch(cusDeviceBreakdownDTO.getCusDocumentListDocument());
        }
        return entity;
    }

    @Override
    public void del(List<Integer> ids) {
        // 校验状态
        QueryWrapper queryWrapperBreakDown = new QueryWrapper<>();
        queryWrapperBreakDown.select("id");
        queryWrapperBreakDown.in("id",ids);
        queryWrapperBreakDown.ne("repaire_status",Const.RepairStatus.STAGING);
        List list = this.list(queryWrapperBreakDown);
        if(list.size()!=0){
            throw new BDException("操作失败，只能删除暂存的故障报修！");
        }

        //删除故障报修
        removeByIds(ids);
        //删除图片关系
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("device_ref_id",ids);
        queryWrapper.eq("device_ref_type",Const.DeviceRefType.DEVICE_BREAKDOWN_FILE);
        cusDocumentService.remove(queryWrapper);
    }

    @Override
    public CusDeviceBreakdownVo getCusDeviceBreakdown(Integer id) {
        CusDeviceBreakdownVo result = new CusDeviceBreakdownVo();
        CusDeviceBreakdown entity = getById(id);
        BeanUtils.copyProperties(entity,result);
        //获取设备
        CusDevice device = cusDeviceService.getById(entity.getDeviceId());
        result.setDeviceNo(device.getDeviceNo());
        result.setDeviceName(device.getDeviceName());
        result.setDeviceAttr(device.getDeviceAttr());
        result.setDeviceLocation(device.getDeviceLocation());
        SysDictionary deviceType = sysDictionaryService.getById(device.getDeviceType());
        result.setDeviceTypeName(deviceType.getDicName());

        //报修时间
        result.setSendRepaireTime(entity.getSendRepaireTime());

        //报修人
        SysUser creat = sysUserService.getById(entity.getCreateBy());
        result.setCreateByName(creat.getRealName());

        //任务等级
        SysDictionary dictionary = sysDictionaryService.getById(entity.getBreakdownLevel());
        if(dictionary!=null){
            result.setBreakdownLevelName(dictionary.getDicName());
        }
        //维修责任人
        SysUser user = sysUserService.getById(entity.getRepaireUserId());
        result.setRepaireUserName(user.getRealName());
        //照片列表
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.select("document_id");
        queryWrapper.eq("device_ref_id",entity.getId());
        queryWrapper.eq("device_ref_type",Const.DeviceRefType.DEVICE_BREAKDOWN_FILE);
        List<CusDocument> documentList = cusDocumentService.list(queryWrapper);
        result.setCusDocumentListDocument(documentList);
        // 图片列表
        if(CollectionUtil.isNotEmpty(documentList)){
            List<Integer> fileIds = documentList.stream()
                    .map(CusDocument::getDocumentId)
                    .collect(Collectors.toList());
            QueryWrapper queryFileWrapper = new QueryWrapper<>();
            queryFileWrapper.in("id",fileIds);
            List<SysFileHis> fileHisList = sysFileHisService.list(queryFileWrapper);
            result.setSysFileHisList(fileHisList);
        }
        //维修记录列表
        result.setRepairList(cusRepaireService.findListByBreakDownId(id));

        // 获取验收意见
        CusRepairApproveDTO cusRepairApproveDTO = cusRepairApproveService.getRepairApproveByBreakDownId(id);
        if(cusRepairApproveDTO!=null){
            result.setApproveContent(cusRepairApproveDTO.getApproveContent());
        }

        return result;
    }

    @Override
    public void changeStatus(Integer breakDownId,
                             Integer repairStatus,
                             Integer repairRecordStatus,
                             Integer repairUserId
                                ) {
        CusDeviceBreakdown entity = getById(breakDownId);
        if(!Objects.equals(entity.getRepaireStatus(),Const.RepairStatus.SUBMIT)){
            throw new BDException("操作失败，该报修已处理，请勿重复处理！");
        }
        //更新报修状态
        if(repairUserId!=null){
            entity.setRepaireUserId(repairUserId);
        }
        entity.setRepaireStatus(repairStatus);
        this.updateById(entity);

        //获取最后一条维修记录
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("breakdown_id",breakDownId);
        queryWrapper.orderByDesc("id");
        List<CusRepaire>  cusRepaireList = cusRepaireService.list(queryWrapper);
        if(CollectionUtil.isNotEmpty(cusRepaireList)){
            CusRepaire cusRepaire = cusRepaireList.get(0);
            cusRepaire.setRepaireStatus(repairRecordStatus);
            cusRepaireService.updateById(cusRepaire);
        }

    }

    @Override
    public void submitDeal(CusRepaireDTO cusRepaireDTO) {
        CusDeviceBreakdown entity = getById(cusRepaireDTO.getBreakdownId());
        if(!Objects.equals(entity.getRepaireStatus(),Const.RepairStatus.SUBMIT)){
            throw new BDException("操作失败，该报修已处理，请勿重复处理！");
        }
        if (!Objects.equals(entity.getRepaireUserId() , TokenUtil.getUserId())) {
            throw new BDException("操作失败，非维修负责人，无法处理维修！");
        }

        //更新维修状态
        cusRepaireDTO.setRepaireStatus(Const.RepairRecordStatus.COMPLETED);

        if(cusRepaireDTO.getId()==null){
            cusRepaireService.dealAddCusRepaire(cusRepaireDTO);
        }else{
            cusRepaireService.dealEditCusRepaire(cusRepaireDTO);
        }

        //更新报修状态
        entity.setRepaireStatus(Const.RepairStatus.PROCESSED_ACCEPTANCE);
        this.updateById(entity);
    }

    @Override
    public CusRepaireVo getRepairDetailByBreakDownId(Integer breakdownId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("breakdown_id",breakdownId);
        queryWrapper.orderByDesc("id");
        List<CusRepaire>  cusRepaireList = cusRepaireService.list(queryWrapper);
        CusRepaireVo result = new CusRepaireVo();
        result.setBreakdownId(breakdownId);
        if(CollectionUtil.isNotEmpty(cusRepaireList)){
            CusRepaire cusRepaire = cusRepaireList.get(0);
            // 最后一条为不通过时，另起一条
            if(Objects.equals(cusRepaire.getRepaireStatus(),Const.RepairRecordStatus.FALLBACK)) {
                return result;
            }
            // 最后一条为转派时，另起一条
            if(Objects.equals(cusRepaire.getRepaireStatus(),Const.RepairRecordStatus.TRANSFERRED)){
                result.setRepaireParentId(cusRepaire.getId());
                return result;
            }
            result = cusRepaireService.getCusRepaire(cusRepaire.getId());

        }
        return result;
    }

}






